import {useStatusBarHidden} from '@/hooks/useStatusBarHidden';
import {Text, TouchableOpacity, View} from 'react-native';
import {useCountDown} from 'ahooks';
import {
  useContext,
  useImperativeHandle,
  useLayoutEffect,
  useState,
} from 'react';
import FastImage from 'react-native-fast-image';
import {useTranslation} from 'react-i18next';
import {AdsVO} from '@/services/api/ads';
import PagerView from 'react-native-pager-view';
import NativeLaunchManager from '~/specs/NativeLaunchManager';
import {AppProperties} from '~/App';
import StringUtils from '@/utils/StringUtils';
import {useAppTheme} from 'tsun-smart-ui';
export default ({
  onPress,
  ads,
  ref,
  setAdsLoaded,
}: {
  onPress: () => void;
  ads: AdsVO;
  ref: React.RefObject<{setIsLoad: (isLoad: boolean) => void} | null>;
  setAdsLoaded: (isLoad: boolean) => void;
}) => {
  const {t} = useTranslation();
  useStatusBarHidden();
  const [targetDate, setTargetDate] = useState<number | undefined>(undefined);
  const {onAnimationComplete} = useContext(AppProperties);
  const theme = useAppTheme();
  const [isLoad, setIsLoad] = useState(false);
  const [count] = useCountDown({
    onEnd: onPress,
    targetDate,
  });
  useImperativeHandle(
    ref,
    () => {
      return {
        setIsLoad,
      };
    },
    [],
  );
  
  useLayoutEffect(() => {
    if ((onAnimationComplete ?? true) && isLoad) {
      setTargetDate(Date.now() + 5000);
      requestAnimationFrame(() => {
        NativeLaunchManager.hide(theme.colors?.background?.primary);
      });
    }
  }, [onAnimationComplete, isLoad]);
  return (
    <View className="flex-1 relative">
      <TouchableOpacity
        className=" absolute right-3 top-10 z-10  bg-slate-800 p-3  rounded-full opacity-80"
        onPress={onPress}>
        <Text className="text-white text-center">
          {t('common.skip') + (count ? Math.round(count / 1000) : 5)}
        </Text>
      </TouchableOpacity>
      <PagerView className="flex-1">
        {ads.map((item, index) => {
          return (
            <View key={index}>
              <FastImage
                className="size-full"
                onLoadEnd={() => {
                  index === 0 && setAdsLoaded(true);
                }}
                resizeMode="contain"
                source={{
                  uri: StringUtils.toImageUri(item.advImageUrl),
                }}></FastImage>
            </View>
          );
        })}
      </PagerView>
    </View>
  );
};
